import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import { showToast } from 'vant'

import HomePage from './pages/HomePage.vue'
import CarPage from './pages/CarPage.vue'
import LoginPage from './pages/LoginPage.vue'
import RegisterPage from './pages/RegisterPage.vue'
import DetailPage from './pages/DetailPage.vue'
import personalPage from './pages/Personal.vue'
import notFoundPage from './pages/404.vue'
import ClassPage from './pages/ClassPage.vue'

// 异步路由
// const notFoundPage = () => import('./pages/404.vue')


const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      component: HomePage,
    },
    {
      path: '/car',
      component: CarPage,
      beforeEnter(to, from) {
        const token = localStorage.getItem('token')

        if (!token) {
          showToast('您未登录，已为您跳转至登录页面')
          return '/login'
        }
      }
    },
    {
      path: '/login',
      component: LoginPage
    },
    {
      path: '/register',
      component: RegisterPage
    },
    {
      path: '/detail/:id',
      component: DetailPage
    },
    {
      path: '/personal',
      component: personalPage,
      beforeEnter(to, from) {
        const token = localStorage.getItem('token')

        if (!token) {
          showToast('您未登录，已为您跳转至登录页面')
          return '/login'
        }
      }
    },
    {
      path: '/404',
      component: notFoundPage
    },
    {
      path: '/classification',
      component: ClassPage,
    }
  ],
})

// 自动跳转到404页面
// to.matched 表示匹配度的路由规则
// 能够匹配到 返回一个数组 内容为路由对象
// 匹配不到 返回空数组
router.beforeEach((to, from) => {
  // 当 to.matched.length == 0 表示匹配不到 返回了空数组
  if (to.matched.length == 0) {
    return '/404'
  }
})

export default router
